package cn.zjxiliu.lib_core.http;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import org.xutils.common.Callback;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by jessie on 2018/10/25.
 */

public abstract class RequestCallback<T> implements ParameterizedType {


    private ResponseBean<T> responseBean;

    private static final String TAG = "RequestCallback";

    @Override
    public Type[] getActualTypeArguments() {
        Class clz = this.getClass();
        //这里必须注意在外面使用new GsonResponsePasare<GsonResponsePasare.DataInfo>(){};实例化时必须带上{},否则获取到的superclass为Object
        Type superclass = clz.getGenericSuperclass(); //getGenericSuperclass()获得带有泛型的父类
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
        return parameterized.getActualTypeArguments();
    }

    @Override
    public Type getRawType() {
        return ResponseBean.class;
    }

    @Override
    public Type getOwnerType() {
        return null;
    }

    public enum ResultCode{
        SUCCESS(200), FAILED(201), TOKEN_FAILED(202), ;

        private int val;

        private ResultCode(int val){
            this.val = val;
        }

        public int getVal() {
            return val;
        }

    }

    public ResponseBean<T> getResult(String data){
        Type gsonType = this;
        ResponseBean<T> result = new Gson().fromJson(data, gsonType);
        return result;
    }


    public void onSuccessCall(String result){
        Logger.i(TAG, result);
        responseBean = getResult(result);
        if(responseBean.resultCode == ResultCode.SUCCESS.getVal()){
            onSuccessCallback(responseBean.content);
        }else if(responseBean.resultCode == ResultCode.TOKEN_FAILED.getVal()){
            onTokenUnusefullCallback();
        }else{
            onFailedCallback(responseBean.resultMsg);
        }
    }



    protected abstract void onTokenUnusefullCallback();

    public void onErrorCall(Throwable ex, boolean isOnCallback) {
        onFailedCallback("网络异常");
    }

    public void onCancelledCall(Callback.CancelledException cex) {
        onCancelledCallback(cex.getMessage());
    }

    public void onFinishedCall() {
        onFinishedCallback();
    }

    protected abstract void onFinishedCallback();

    public abstract void onSuccessCallback(T t);

    public abstract void onFailedCallback(String errorMsg);

    public abstract void onCancelledCallback(String message);
}
